'''
Created on Sep 29, 2011

@author: f13
'''
import serial, Config, Logger, Packet
from multiprocessing import Process

config = Config.config

class CommunicationManager():
    def __init__(self, packetQueue):
        self.logger = Logger.logger.communicationsLogger
        self.logger.log(1, "Logger initialized successfully.")        
        # Initialize serial connection and listen server
        self.serialConnection = serial.Serial(config.serialPort, config.serialRate)
        self.logger.log(2, "Serial connection established.")
        self.listenProcess = Process(target=self.receivePackets, args=(self.serialConnection, packetQueue))
        self.listenProcess.start()
        self.logger.log(1, "Listen process initialized successfully.")
        
    def receivePackets(self, serialConnection, packetQueue):
        while True:
            currentPacket = serialConnection.readline()
            if len(currentPacket) == config.packetSize + config.newLineSize:
                #Create an instance of Packet
                temporaryPacket = Packet.Packet()
                #Fill the packet with the correct information
                temporaryPacket.fillPacket(currentPacket)
                #push the packet into the packet Queue
                print "Receiving Packet: " + temporaryPacket.toString()
                packetQueue.put(temporaryPacket)
                
    def sendPacket(self, packet):
        self.serialConnection.write(packet.toString())
        print "Sending Packet: " + packet.toString()
    
    def kill(self):
        self.listenProcess.terminate()
        self.logger.log(1, "Listen process terminated successfully.")